package com.hanlin.day04;

/**
 * 描述：链表实现队列
 *
 * @author:hl.yuan
 * @date:2022-06-14
 */
public class LinkedListQueue<V> {

    public static class Node<T> {
        public Node next;
        public T value;

        public Node(T value) {
            this.value = value;
        }
    }

    /**
     * 头 节点
     */
    private Node<V> head;
    /**
     * 尾节点
     */
    private Node<V> tail;
    private int size;

    /**
     * 查看是否存在元素
     *
     * @return
     */
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * 队列长度
     *
     * @return
     */
    public int size() {
        return size;
    }

    /**
     * 入列
     */
    public void offer(V node) {
        Node<V> cur = new Node<V>(node);
        // 第一次添加，就设置头节点和尾节点一致
        if (head == null) {
            head = cur;
            tail = cur;
        } else {
            // 尾部的下一个节点，指向当前节点
            tail.next = cur;
            // 把当前节点赋值给尾部，相当于尾部节点向后位移一位
            tail = cur;
        }
        size++;
    }

    /**
     * 出列
     *
     * @return
     */
    public V poll() {
        V val = null;
        if (head != null) {
            val = head.value;
            head = head.next;
            size--;
        }
        if (head == null) {
            tail = null;
            size = 0;
        }
        return val;
    }

    /**
     * 查看下一个元素
     *
     * @return
     */
    public V peek() {
        V val = null;
        if (head != null) {
            val = head.value;
        }
        return val;
    }

}



